package cn.yuanqiao.archive.wenjianzhengli.utils;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantYqdaDocument;
import cn.yuanqiao.archive.detection.util.EncryptionUtil;
import cn.yuanqiao.archive.webservice.utils.WebServiceFileUtils;
import cn.yuanqiao.common.exception.file.FileException;
import cn.yuanqiao.common.exception.file.FileNameLengthLimitExceededException;
import cn.yuanqiao.common.exception.file.FileSizeLimitExceededException;
import cn.yuanqiao.common.exception.file.InvalidExtensionException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.file.FileTypeUtils;
import cn.yuanqiao.common.utils.file.MimeTypeUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 文件上传工具类
 * 
 * @author ruoyi
 */
public class FileUploadUtils
{

    /**
     * 默认大小 200M
     */
    public static long DEFAULT_MAX_SIZE = 200 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认可上传文件类型
     */
    public static String [] DEFAULT_ALLOWED_EXTENSION = MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION;

    private static DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 上传文件配置
     * @param maxSize 文件大小
     * @param extensions 文件类型
     */
    public static void setDefaultConfig(String maxSize,String extensions){
        if(StringUtils.isNotEmpty(maxSize)){
            DEFAULT_MAX_SIZE = Long.valueOf(maxSize) * 1024 * 1024;
        }else {
            DEFAULT_MAX_SIZE = 200 * 1024 * 1024;
        }
        if(StringUtils.isNotEmpty(extensions)){
            DEFAULT_ALLOWED_EXTENSION = extensions.split(",");
        }else {
            DEFAULT_ALLOWED_EXTENSION = MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION;
        }

    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final TenantYqdaDocument upload(TenantCategory category, Integer type , Long daId, Integer orderNo, String baseDir, MultipartFile file) throws IOException
    {
        try
        {
            return upload(category,type,daId,orderNo,baseDir, file, DEFAULT_ALLOWED_EXTENSION);
        }
        catch (FileException fe)
        {
            throw new IOException(fe.getDefaultMessage(), fe);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException 比如读写文件出错时
     * @throws InvalidExtensionException 文件校验异常
     */
    public static final TenantYqdaDocument upload(TenantCategory category, Integer type , Long daId, Integer orderNo, String baseDir, MultipartFile file, String[] allowedExtension)
            throws Exception {
        int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);
        String filePath = extractPath(category,daId);
        String fileName = extractFilename(type,daId,orderNo,file);
        //baseDir = /opt/mnt/
        String absPath = getAbsoluteFile(baseDir+filePath, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        //获取文件创建时间作为上传时间
        // 获取文件创建时间
        // 获取文件属性
        BasicFileAttributes attributes = Files.readAttributes(Paths.get(absPath), BasicFileAttributes.class);
        // 获取文件创建时间
        FileTime createTime = attributes.creationTime();
       // 将文件创建时间转换为标准格式
        String dateFormat = df.format(createTime.toMillis());
        TenantYqdaDocument document = new TenantYqdaDocument();
        Map<String,String> colNum = new HashMap<>();
        colNum.put("PATH",filePath+fileName);
        colNum.put("DOC_ORDER",orderNo.toString());
        colNum.put("DOC_NAME",file.getOriginalFilename());
        colNum.put("DOC_FILE_TYPE",FileTypeUtils.getExtension(file).toUpperCase());
        colNum.put("IS_DEL","0");
        colNum.put("ACTION_TIME",dateFormat);
        colNum.put("CREATE_TIME",DateUtils.getTime());
        colNum.put("DOC_FILE_SIZE",String.valueOf(file.getSize()));
        colNum.put("IS_INDEX","0");
        colNum.put("TYPE",type.toString());
        colNum.put("REAL_DOC_NAME",fileName);
        colNum.put("DOC_MNT",baseDir);
        colNum.put("TO_OFD","0");
        colNum.put("DOC_CREATE_TIME",getDocCreateTime(new File(absPath)));
        //拿到SM3的hash 以及 MD5的hash
        colNum.put("FILE_ONLY_VAL", WebServiceFileUtils.getFileMD5(new File(absPath)));
        colNum.put("FILE_ONLY_VAL_GM", EncryptionUtil.getSM3Hash(absPath));
        document.setColNames(colNum);
        return document;
    }

    public static final String getDocCreateTime(File file){
        String time = "";
        try {
            BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            long creationTime = attributes.creationTime().toMillis();
            time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date(creationTime));
            //System.out.println("File creation time: " + creationTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }


    public static final String extractPath(TenantCategory category, Long daId)
    {
        StringBuilder path = new StringBuilder().append(category.getFondsCode()).append(File.separator).append(category.getCode()).append(File.separator).
                append(daId).append(File.separator);
        return path.toString();
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(Integer type , Long daId, Integer orderNo, MultipartFile file)
    {
        String fileName = daId+"0"+type+"A"+ (orderNo<999 ? (orderNo<99 ? (orderNo<9 ? "00"+orderNo:("0"+orderNo)):orderNo):orderNo);
        StringBuilder path = new StringBuilder().append(fileName).append(".").append(FileTypeUtils.getExtension(file));
        return path.toString();
    }

    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }

    private static final String getPathFileName(String fileName) throws IOException
    {
        String pathFileName = "/" + fileName;
        return pathFileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException 文件校验异常
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException
    {
        long size = file.getSize();
        if (size > DEFAULT_MAX_SIZE)
        {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }

        String fileName = file.getOriginalFilename();
        String extension = FileTypeUtils.getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
        {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            }
            else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            }
            else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            }
            else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
                        fileName);
            }
            else
            {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension 上传文件类型
     * @param allowedExtension 允许上传文件类型
     * @return true/false
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
    {
        for (String str : allowedExtension)
        {
            if (str.equalsIgnoreCase(extension))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException 文件校验异常
     */
    public static final void fileAllowed(MultipartFile file)
            throws FileSizeLimitExceededException, InvalidExtensionException
    {
        long size = file.getSize();
        if (size > DEFAULT_MAX_SIZE)
        {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }

        String fileName = file.getOriginalFilename();
        String extension = FileTypeUtils.getExtension(file);
        if (DEFAULT_ALLOWED_EXTENSION != null && !isAllowedExtension(extension, DEFAULT_ALLOWED_EXTENSION))
        {
            if (DEFAULT_ALLOWED_EXTENSION == MimeTypeUtils.IMAGE_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidImageExtensionException(DEFAULT_ALLOWED_EXTENSION, extension,
                        fileName);
            }
            else if (DEFAULT_ALLOWED_EXTENSION == MimeTypeUtils.FLASH_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidFlashExtensionException(DEFAULT_ALLOWED_EXTENSION, extension,
                        fileName);
            }
            else if (DEFAULT_ALLOWED_EXTENSION == MimeTypeUtils.MEDIA_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidMediaExtensionException(DEFAULT_ALLOWED_EXTENSION, extension,
                        fileName);
            }
            else if (DEFAULT_ALLOWED_EXTENSION == MimeTypeUtils.VIDEO_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidVideoExtensionException(DEFAULT_ALLOWED_EXTENSION, extension,
                        fileName);
            }
            else
            {
                throw new InvalidExtensionException(DEFAULT_ALLOWED_EXTENSION, extension, fileName);
            }
        }
    }
}